<template>
  <div class="customer">
    <n-button type="primary" size="small" @click="methods.addCustomer">添加</n-button>
    <n-form-item
      v-if="list.length"
      :path="`${pathKey}`"
      :rule="{ validator: methods.validatorCustomer }"
    >
      <div class="cardList">
        <div v-for="(item, index) in list" :key="index" class="cardItem">
          <img
            class="closeCustomer"
            src="@/assets/icons/close.png"
            @click="methods.removeCustomer(index)"
          />
          <n-grid :x-gap="12" :cols="24">
            <n-gi :span="8">
              <n-form-item label="客户名称" :path="`${pathKey}[${index}].flag`">
                <AsyncSelect
                  v-model:value="item.flag"
                  :options="data.typeOptions"
                  :clearable="false"
                  @update:value="methods.resetCustomer(index)"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="16">
              <n-form-item
                v-if="item.flag === 'CUSTOMER_FLAG_CHOOSE'"
                :path="`${pathKey}[${index}].id`"
                :rule="{ required: true, message: '请选择客户' }"
              >
                <AsyncSelect
                  v-model:value="item.id"
                  :options="methods.getCustomerOptions"
                  remote
                  :init-remote="true"
                  label-key="name"
                  value-key="id"
                  @update:value="methods.resetReceiver(index)"
                />
              </n-form-item>
              <n-form-item
                v-if="item.flag === 'CUSTOMER_FLAG_ADD'"
                :path="`${pathKey}[${index}].name`"
                :rule="{ required: true, message: '请输入客户' }"
              >
                <n-input v-model:value="item.name" maxlength="30" clearable show-count />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-form-item
            label="对接人"
            :path="`${pathKey}[${index}].contactorDtoList`"
            :rule="{
              validator: (rule, value, callback) =>
                methods.validatorContactor(rule, value, callback, item.flag),
            }"
          >
            <Contacter
              v-model="item.contactorDtoList"
              :path-key="`${pathKey}[${index}].contactorDtoList`"
              :customer-flag="item.flag"
              :customer-id="item.id"
            />
          </n-form-item>
        </div>
      </div>
    </n-form-item>
  </div>
</template>
<script setup lang="jsx">
import * as customerApi from '@/api/customer'
const list = defineModel({ type: Array, default: () => [] })
defineProps({
  pathKey: {
    type: String,
    default: 'customerManagementDtoList',
  },
})

const data = reactive({
  typeOptions: [
    { label: '选择客户', value: 'CUSTOMER_FLAG_CHOOSE' },
    { label: '新增客户', value: 'CUSTOMER_FLAG_ADD' },
  ],
})
const methods = reactive({
  validatorCustomer(_, value, callback) {
    if (Array.isArray(value)) {
      const trueLength = [...new Set(value.map((item) => item.id).filter((id) => id))].length
      if (trueLength && trueLength !== value.filter((item) => item.id).length) {
        callback(new Error('存在重复客户'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  },
  validatorContactor(_, val, callback, flag) {
    if (Array.isArray(val)) {
      const map = {
        CUSTOMER_FLAG_CHOOSE: 'id',
        CUSTOMER_FLAG_ADD: 'contactorName',
      }
      const exist = val.filter((item) => item[map[flag]] && item.status !== 'DELETED')
      const norepeat = [...new Set(exist.map((item) => item[map[flag]]))]
      if (norepeat.length !== exist.length) {
        callback(new Error('存在重复对接人'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  },
  getCustomerOptions(searchVal, id) {
    return customerApi.listAll({ searchVal, id }).then((res) => res.data)
  },
  customerMold() {
    return {
      flag: 'CUSTOMER_FLAG_CHOOSE',
      id: null,
      name: null,
      contactorDtoList: [],
    }
  },
  addCustomer() {
    list.value.push(methods.customerMold())
  },
  removeCustomer(index) {
    list.value.splice(index, 1)
  },
  resetCustomer(index) {
    Object.assign(list.value[index], {
      id: null,
      name: null,
      contactorDtoList: [],
    })
  },
  resetReceiver(index) {
    Object.assign(list.value[index], {
      contactorDtoList: [],
    })
  },
})
</script>
<style lang="scss" scoped>
.customer {
  width: 100%;
  .cardList {
    display: flex;
    flex-direction: column;
    text-align: start;
    gap: 10px;
    margin-top: 10px;
    .cardItem {
      padding: 32px 16px 16px;
      border-radius: 4px;
      background: rgba(244, 245, 247, 1);
      position: relative;
      .closeCustomer {
        width: 16px;
        height: 16px;
        position: absolute;
        top: 8px;
        right: 16px;
        cursor: pointer;
      }
    }
  }
}
</style>
